package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-data-hub/cache"
	"novel-data-hub/models"
	"strconv"
	"time"
)

func DeliveryOrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size

	/*
		SELECT
		  delivery_orders.id as OrderId,
		  deliveries.del_code as DelCode,
		  deliveries.del_name as DelName,
		  deliveries.del_phone as DelPhone,
		  delivery_orders.order_code as OrderCode,
		  delivery_orders.order_place as OrderPlace,
		  delivery_orders.order_num as OrderNum
		FROM
		  deliveries
		  LEFT JOIN delivery_orders ON delivery_orders.del_id = deliveries.id
		WHERE
		  delivery_orders.id = 1
	*/
	var list []models.DeliveryOrderList
	redis_key := "delivery_order_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("deliveries").
			Select("delivery_orders.id as OrderId",
				"deliveries.del_code as DelCode",
				"deliveries.del_name as DelName",
				"deliveries.del_phone as DelPhone",
				"delivery_orders.order_code as OrderCode",
				"delivery_orders.order_place as OrderPlace",
				"delivery_orders.order_num as OrderNum",
			).
			Joins("LEFT JOIN delivery_orders ON delivery_orders.del_id = deliveries.id").
			Offset(offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var count int64
	models.DB.Model(&models.DeliveryOrder{}).Count(&count)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  list,
		"count": count,
	})
	return
}

func DeliveryOrderDetail(c *gin.Context) {
	id := c.Query("id")

	var list models.DeliveryOrderList
	redis_key := "delivery_order_list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("deliveries").
			Select("delivery_orders.id as OrderId",
				"deliveries.del_code as DelCode",
				"deliveries.del_name as DelName",
				"deliveries.del_phone as DelPhone",
				"delivery_orders.order_code as OrderCode",
				"delivery_orders.order_place as OrderPlace",
				"delivery_orders.order_num as OrderNum",
			).
			Joins("LEFT JOIN delivery_orders ON delivery_orders.del_id = deliveries.id").
			Where("delivery_orders.id = ?", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": list,
	})
	return
}
